package logic
{
	import com.codezen.helper.Worker;
	import com.codezen.util.CUtils;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	
	import mx.controls.Alert;
	
	import utils.anime.AniEpisode;
	import utils.anime.AniSerial;

	/**
	 * 
	 * @author Light
	 * 
	 * Data loader class
	 */
	public class AnimeDataLoader extends Worker
	{
		// user login and pass
		private static var userLogin:String;
		private static var userPass:String;
		
		// data loaders
		private var request:URLRequest;
		private var loader:URLLoader;
		
		// data vars
		private var lastEps:Vector.<AniEpisode>;
		private var series:Vector.<AniSerial>;
		private var episodes:Vector.<AniEpisode>;
		
		/**
		 * 
		 * @param login
		 * @param pass
		 * 
		 * Constructor
		 */
		public function AnimeDataLoader(login:String, pass:String)
		{
			// save login and pass
			userLogin = login;
			userPass = pass;
			
			// init vars
			// create urlrequest and urlloader
			request = new URLRequest();
			loader = new URLLoader();
			// set prefs, add error event listener 
			loader.dataFormat = URLLoaderDataFormat.TEXT;
			loader.addEventListener(IOErrorEvent.IO_ERROR, onRequestError);
			
			// try loggin in
			tryLogin();
		}
		
		/**
		 * Loads series data by ID 
		 * @param id
		 * 
		 */
		public function loadSeries(id:String):void{
			// add
			loader.addEventListener(Event.COMPLETE, onSeriesData);
			
			// from urlrequest and urlloader
			request.url = "http://tulavideo.net/xml/ShowAnime/"+id+"/";
			// load
			loader.load(request);
		}
		
		/**
		 * Gets last eps 
		 * @return 
		 * 
		 */
		public function get lastEpisodes():Vector.<AniEpisode>{
			return lastEps;
		}
		
		/**
		 * Gets series list 
		 * @return 
		 * 
		 */
		public function get seriesList():Vector.<AniSerial>{
			return series;
		}
		
		public function get episodesList():Vector.<AniEpisode>{
			return episodes;
		}
		
		/**
		 * Try loggin in 
		 * 
		 */
		private function tryLogin():void{
			// add event listener 
			loader.addEventListener(Event.COMPLETE, onLoginAttempt);
			
			// vars
			var variables:URLVariables = new URLVariables();
			variables.AUTH_USER = userLogin;
			variables.AUTH_PW = userPass;
			
			// from urlrequest and urlloader
			request.url = "http://tulavideo.net/xml/Start/";
			request.data = variables;
			request.method = URLRequestMethod.POST;
			// load
			loader.load(request);
		}
		
		/**
		 * Series data recieve callback 
		 * @param e
		 * 
		 */
		private function onSeriesData(e:Event):void{
			// remove event listener
			loader.removeEventListener(Event.COMPLETE, onSeriesData);
			
			episodes = new Vector.<AniEpisode>();
			
			// create result XML
			var data:XML = new XML(e.target.data);
			
			var list:XMLList = data.manime.anime.children();
			
			// serial data
			var serial_id:String = data.manime.anime.info.item.id_aseries;
			var serial_title:String = data.manime.anime.info.item.title;
			var serial_etitle:String = data.manime.anime.info.item.etitle;
			var serial_jtitle:String = data.manime.anime.info.item.jtitle;
			var serial_simg:String = "http://www.tulavideo.net/"+data.manime.anime.info.item.simg;
			var serial_bimg:String = "http://www.tulavideo.net/"+data.manime.anime.info.item.bimg;
			var serial_info:String = htmlUnescape(data.manime.anime.info.item.info);

			// parse
			var ep:AniEpisode;
			var i:int;
			var subitem:Object;
			for(i = 1; i < list.length(); i++){
				for each(subitem in list[i].children()){
					// new
					ep = new AniEpisode();
					// serial data
					ep.serial_id = serial_id;
					ep.serial_etitle = serial_etitle;
					ep.serial_jtitle = serial_jtitle;
					ep.serial_title = serial_title;
					ep.serial_info = serial_info;
					ep.serial_simg = serial_simg;
					ep.serial_bimg = serial_bimg;
					// ep data
					ep.id = subitem.id_aepisodes;
					ep.aid = subitem.id;
					ep.season = subitem.s; 
					ep.num = subitem.n;
					ep.title = subitem.title;
					ep.jtitle = subitem.jtitle;
					ep.image = "http://anime.tulavideo.net/"+ep.serial_id+"/"+ep.aid+".jpg";
					ep.video = "http://anime.tulavideo.net/"+ep.serial_id+"/"+ep.aid+".mp4";
					// 'http://anime.tulavideo.net/2/01-26_1.srt
					ep.snd1 = subitem.snd1;
					ep.snd2 = subitem.snd2;
					ep.sub1 = subitem.sub1;
					ep.sub2 = subitem.sub2;
					ep.tmark = subitem.tmark;
					// push
					episodes.push(ep);
				}
			}
			
			// clean
			data = null;
			list = null;
			serial_id = null;
			serial_title = null;
			serial_etitle = null;
			serial_jtitle = null;
			serial_simg = null;
			serial_bimg = null;
			serial_info = null;
			ep = null;
			subitem = null;
			
			// end
			endLoad();
		}
		
		/**
		 * On login data recieve 
		 * @param e
		 * 
		 */
		private function onLoginAttempt(e:Event):void{
			// remove event listener
			loader.removeEventListener(Event.COMPLETE, onLoginAttempt);
			
			// create result XML
			var data:XML = new XML(e.target.data);
			
			if(data.user.children().length() != 0){
				// parse new episodes
				setLastEpisodes(data);
				// dispatch inited event
				dispatchEvent(new Event(Event.INIT));
				//requestData();
			}else{
				dispatchError("Логин или пароль введены неверно!");
			}
		}
		
		/**
		 * Parses input data for latest episods from news XML 
		 * @param data
		 * 
		 */
		private function setLastEpisodes(data:XML):void{
			lastEps = new Vector.<AniEpisode>();
			
			// serial data
			var serial_id:String;
			var serial_title:String;
			var serial_etitle:String;
			var serial_jtitle:String;
			var serial_simg:String;
			var serial_bimg:String;
			var serial_info:String;
			
			// get list
			var list:XMLList = data.last.anime.children();
			// temp vars
			var ep:AniEpisode;
			var item:XML;
			var subitem:XML;
			// for each item parse to array
			for each(item in list){
				// if node is not empty
				if(item.children().length() > 0){
					serial_id = item.aseries.item.id_aseries;
					serial_title = item.aseries.item.title;
					serial_etitle = item.aseries.item.etitle;
					serial_jtitle = item.aseries.item.jtitle;
					serial_info = htmlUnescape(item.aseries.item.info);
					serial_simg = "http://www.tulavideo.net/"+item.aseries.item.simg;
					serial_bimg = "http://www.tulavideo.net/"+item.aseries.item.bimg;
					
					// parse episodes
					for each(subitem in item.descendants("item")){
						if( String(subitem.id).length > 0 ){
							// new episode
							ep = new AniEpisode();
							// serial data
							ep.serial_id = serial_id;
							ep.serial_etitle = serial_etitle;
							ep.serial_jtitle = serial_jtitle;
							ep.serial_title = serial_title;
							ep.serial_info = serial_info;
							ep.serial_simg = serial_simg;
							ep.serial_bimg = serial_bimg;
							// ep data
							ep.id = subitem.id_aepisodes;
							ep.aid = subitem.id;
							ep.season = subitem.s; 
							ep.num = subitem.n;
							ep.title = subitem.title;
							ep.jtitle = subitem.jtitle;
							ep.image = "http://anime.tulavideo.net/"+ep.serial_id+"/"+ep.aid+".jpg";
							ep.video = "http://anime.tulavideo.net/"+ep.serial_id+"/"+ep.aid+".mp4";
							// 'http://anime.tulavideo.net/2/01-26_1.srt
							ep.snd1 = subitem.snd1;
							ep.snd2 = subitem.snd2;
							ep.sub1 = subitem.sub1;
							ep.sub2 = subitem.sub2;
							ep.tmark = subitem.tmark;
						
							// push to arr
							lastEps.push(ep);
						}
					}
				}
			}
			
			// end set
			// clean
			list = null;
			serial_id = null;
			serial_title = null;
			serial_etitle = null;
			serial_jtitle = null;
			serial_simg = null;
			serial_bimg = null;
			serial_info = null;
			ep = null;
			item = null;
			subitem = null;
		}
		
		public function requestData():void{
			loader.addEventListener(Event.COMPLETE, onDataLoad);
			
			// from urlrequest and urlloader
			request.url = "http://tulavideo.net/xml/ShowAnimes/";
			// load
			loader.load(request);
		}
		
		private function onDataLoad(e:Event):void{
			// remove event listener
			loader.removeEventListener(Event.COMPLETE, onDataLoad);
			
			// create result XML
			var data:XML = new XML(e.target.data);
			var list:XMLList = data.manime.aseries.children();
			
			// init 
			series = new Vector.<AniSerial>();
			
			// parse
			var s:AniSerial;
			var item:Object;
			for each(item in list){
				//create 
				s = new AniSerial();
				// data
				s.id = item.id_aseries;
				s.title = item.title;
				s.etitle = item.etitle;
				s.jtitle = item.jtitle;
				s.simg = "http://www.tulavideo.net/"+item.simg;
				s.bimg = "http://www.tulavideo.net/"+item.bimg;
				s.info = htmlUnescape(item.info);
				// add
				series.push(s);
			}
			
			// end set
			// clean
			list = null;
			s = null;
			item = null;
			data = null;
			
			// end
			endLoad();
		}
		
		private function onRequestError(e:Event):void{
			Alert.show(e.toString(),"Ошибка подключения!");
			//trace(e.toString());
		}
		
		
		private function htmlUnescape(str:String):String{
			return CUtils.convertHTMLEntities( CUtils.stripTags(str) );
		}
	}
}